package com.meiyuetao.myt.customer.web.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.web.json.HibernateAwareObjectMapper;
import lab.s2jh.core.web.view.OperationResult;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.struts2.rest.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.meiyuetao.myt.core.web.MytBaseController;
import com.meiyuetao.myt.customer.entity.WeixinMsg;
import com.meiyuetao.myt.customer.entity.WeixinMsgReply;
import com.meiyuetao.myt.customer.entity.WeixinMsgReply.ReplyTypeEnum;
import com.meiyuetao.myt.customer.service.WeixinMsgReplyService;
import com.meiyuetao.myt.customer.service.WeixinMsgService;

@MetaData("WeixinMsgController")
public class WeixinMsgController extends MytBaseController<WeixinMsg, Long> {
    @Value("${weixin.appid}")
    private String appid;
    @Value("${weixin.secret}")
    private String secret;
    @Value("${weixin.tokenUrl}")
    private String tokenUrl;
    @Value("${weixin.sendUrl}")
    private String sendUrl;
    @Autowired
    private WeixinMsgService weixinMsgService;
    @Autowired
    private WeixinMsgReplyService weixinMsgReplyService;

    @Override
    protected BaseService<WeixinMsg, Long> getEntityService() {
        return weixinMsgService;
    }

    @Override
    protected void checkEntityAclPermission(WeixinMsg entity) {
        // Nothing
    }

    @Override
    @MetaData("保存")
    public HttpHeaders doSave() {
        return super.doSave();
    }

    @Override
    @MetaData("查询")
    public HttpHeaders findByPage() {
        return super.findByPage();
    }

    public HttpHeaders doSend() {
        String access_token = getToken();
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        CloseableHttpClient client = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(sendUrl);
        String replyMsg = this.getRequest().getParameter("replyMsg");
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("access_token", access_token));
        formparams.add(new BasicNameValuePair("touser", bindingEntity.getFromWeixinName().trim()));
        formparams.add(new BasicNameValuePair("msgtype", ReplyTypeEnum.text.name()));
        // formparams.add(new BasicNameValuePair("text", "{'content':'" +
        // replyMsg + "'}"));
        formparams.add(new BasicNameValuePair("content", replyMsg));
        String response = null;
        try {
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httpPost.setEntity(urlEncodedFormEntity);
            HttpResponse httpResponse;
            // post请求
            httpResponse = client.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                response = EntityUtils.toString(httpEntity, "UTF-8");
            }
            client.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        WeixinMsgReply weixinMsgReply = new WeixinMsgReply();
        weixinMsgReply.setWeixinMsg(bindingEntity);
        weixinMsgReply.setReplyTime(new Date());
        weixinMsgReply.setReplyMsg(replyMsg);
        weixinMsgReply.setReplyType(ReplyTypeEnum.text);
        weixinMsgReply.setReplyUser(getLogonUser());
        weixinMsgReply.setMemo(response);
        weixinMsgReplyService.save(weixinMsgReply);
        setModel(OperationResult.buildSuccessResult("发送完成:" + response));
        return buildDefaultHttpHeaders();
    }

    private String getToken() {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        CloseableHttpClient client = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(tokenUrl);
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("appid", appid));
        formparams.add(new BasicNameValuePair("secret", secret));
        String response = null;
        try {
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httpPost.setEntity(urlEncodedFormEntity);
            HttpResponse httpResponse;
            // post请求
            httpResponse = client.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            if (httpEntity != null) {
                response = EntityUtils.toString(httpEntity, "UTF-8");
            }
            client.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        ObjectMapper objectMapper = HibernateAwareObjectMapper.getInstance();
        Map<String, String> map = new HashMap<String, String>();
        try {
            map = objectMapper.readValue(response, Map.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return map.get("access_token");
    }

    @MetaData(value = "微信信息回复")
    public HttpHeaders weixinMsgReplies() {
        List<WeixinMsgReply> weixinMsgReplies = bindingEntity.getWeixinMsgReplies();
        setModel(buildPageResultFromList(weixinMsgReplies));
        return buildDefaultHttpHeaders();
    }

    public String getAppid() {
        return appid;
    }

    public void setAppid(String appid) {
        this.appid = appid;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public String getTokenUrl() {
        return tokenUrl;
    }

    public void setTokenUrl(String tokenUrl) {
        this.tokenUrl = tokenUrl;
    }

    public String getSendUrl() {
        return sendUrl;
    }

    public void setSendUrl(String sendUrl) {
        this.sendUrl = sendUrl;
    }

}